﻿using System;
using System.Threading;
using System.Windows.Forms;

using ProfileManager.DataAccess;
using ProfileManager.Helpers;
using ProfileManager.Properties;

namespace ProfileManager.Forms
{
    public partial class LoginForm : MasterForm
    {
        private delegate void ParamsFreeVoidCallback();

        public LoginForm()
        {
            InitializeComponent();
            
            ShowCustomRightButton = false;
        }

        private Guid Login()
        {
            string login = tbLogin.Text.Trim();
            string password = tbPassword.Text.Trim();

            if (!string.IsNullOrEmpty(login) && !string.IsNullOrEmpty(password))
            {
                return UserInfo.UserLogin(login, password);
            }
            ShowMessage.Error(Resources.SetLoginAndPassword);
            return Guid.Empty;
        }

        private void Start()
        {
            HeaderImage = Resources.Emblems_emblem_unlocked_icon;
            new Thread(ShowMainForm).Start();
        }

        private void ShowMainForm()
        {
            Thread.Sleep(100);
            
            if (InvokeRequired)
            {
                ParamsFreeVoidCallback method = ShowMainForm;
                Invoke(method);
                return;
            }
            
            Hide();

            MainForm mcf = new MainForm();
            if (mcf.ShowDialog() == DialogResult.Cancel)
            {
                Application.Exit();
            }
        }

        private void LoginFormLoad(object sender, EventArgs e)
        {
#if DEBUG
            tbLogin.Text = "test";
            tbPassword.Text = "testtest";
#endif
        }

        private void LoginFormClickCancel(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void LoginFormClickOk(object sender, EventArgs e)
        {
            Guid userId = Login();
            if (userId != Guid.Empty)
            {
                Globals.CurrentUser = UserInfo.Select(userId);
                if (Globals.CurrentUser != null)
                {
                    Start();
                }
                else
                {
                    ShowMessage.Error(Resources.ErrorUserInfoReading);
                }
            }
        }

        private void LoginFormClickCustomLeft(object sender, EventArgs e)
        {
            UserInfoForm userInfoForm = new UserInfoForm();
            userInfoForm.IsNewUser = true;
            if (userInfoForm.ShowDialog() == DialogResult.OK)
            {
                
            }
        }
    }
}